package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.server.protocol.Command;
import cn.wen.yinxiu.member.server.protocol.talk.TalkNoticeRequest;
import cn.wen.yinxiu.member.server.protocol.talk.TalkNoticeResponse;
import cn.wen.yinxiu.member.service.UsersService;
import cn.wen.yinxiu.member.vo.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * @ClassName: TalkNoticeHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 对话通知应答处理
 */
@Slf4j
public class TalkNoticeHandler extends SimpleChannelInboundHandler<TalkNoticeRequest> {

    private final UsersService userService;

    public TalkNoticeHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TalkNoticeRequest msg) throws Exception {
        log.info("对话通知应答处理：{}", JSON.toJSONString(msg));

        switch (msg.getTalkType()) {
            case 0:
                // 1. 对话框数据落库
                userService.addTalkBoxInfo(msg.getUserId(), msg.getTalkId(), 0);
                userService.addTalkBoxInfo(msg.getTalkId(), msg.getUserId(), 0);
                // 2. 查询对话框信息[将自己发给好友的对话框中]
                UserInfo userInfo = userService.queryUserInfo(msg.getUserId());
                // 3. 发送对话框消息给好友
                TalkNoticeResponse response = new TalkNoticeResponse();
                response.setTalkId(userInfo.getUserId());
                response.setTalkName(userInfo.getNickname());
                response.setTalkAvatar(userInfo.getUserAvatar());
                response.setTalkSketch(null);
                response.setTalkTime(new Date());
                // 获取好友通信管道
                Channel friendChannel = SocketChannelUtil.getChannel(msg.getTalkId());
                if (null == friendChannel) {
                    log.info("用户id：{}未登录！", msg.getTalkId());
                    return;
                }
                friendChannel.writeAndFlush(new TextWebSocketFrame(getByteBuf(channelHandlerContext, msg.getTalkId(), response)));
                break;
            case 1:
                userService.addTalkBoxInfo(msg.getUserId(), msg.getTalkId(), 1);
                break;
            default:
                break;
        }
    }

    public ByteBuf getByteBuf(ChannelHandlerContext ctx, Long userId, TalkNoticeResponse talkNoticeResponse) {
        ByteBuf bytebuf = ctx.alloc().buffer();
        JSONObject data = new JSONObject();
        data.put("type", Command.TalkNoticeResponse);
        data.put("code", 200);
        JSONObject params = new JSONObject();
        params.put("userId", userId);
        params.put("talkNoticeInfo", talkNoticeResponse);
        data.put("data", params);
        log.info("登录成功后的返回数据：{}", data);
        byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        bytebuf.writeBytes(bytes);
        log.info("{}", bytebuf);
        return bytebuf;
    }
}
